package flc.ast.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.media.recorder.AudioRecorder;
import com.stark.media.recorder.IRecStateListener;
import com.stark.media.recorder.RecState;
import com.stark.piano.lib.widget.PianoConst;
import com.stark.piano.lib.widget.PianoSeekBar;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.bean.PracticeTime;
import flc.ast.databinding.ActivityPianoBinding;
import flc.ast.dialog.RecordDialog;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import flc.ast.utils.PracticeDatabase;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.TimeUtil;

public class PianoActivity extends BaseAc<ActivityPianoBinding> implements IRecStateListener {

    private AudioRecorder mRecorder;
    private long today, startTime, endTime;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            long duration = mRecorder.getRecDuration();
            String strTime = TimeUtil.getMmss(duration);
            mDataBinding.tvPianoRecordTime.setText(strTime);
            mHandler.postDelayed(this, 1000);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_piano;
    }

    @Override
    protected void initView() {
        mHandler = new Handler();
        mDataBinding.ivPianoBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.ivPianoSelMusic.setOnClickListener(this);
        mDataBinding.ivPianoRecordList.setOnClickListener(this);
        mDataBinding.llPianoRecord.setOnClickListener(this);
        mDataBinding.ivPianoAdd.setOnClickListener(this);
        mDataBinding.ivPianoReduce.setOnClickListener(this);
        mDataBinding.pianoSeekBar.setProgressChangeListener(new PianoSeekBar.IProgressChangeListener() {
            @Override
            public void onProgressChanged(float percent) {
                mDataBinding.pianoKeyBoard.move(percent);
            }
        });
        mDataBinding.pianoSeekBar.setRatioKeyCountInScreen(mDataBinding.pianoKeyBoard.getRatioKeyCountInScreen());
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPianoSelMusic://选择音乐
                startActivity(MusicListActivity.class);
                break;
            case R.id.llPianoRecord:  // 点击开始录制
                if (mRecorder.isIdle()) {
                    StkPermissionHelper.permission(Manifest.permission.RECORD_AUDIO)
                            .reqPermissionDesc(getString(R.string.get_record_permission))
                            .callback(new StkPermissionHelper.ACallback() {
                                @Override
                                public void onGranted() {
                                    mRecorder.start();
                                }
                            })
                            .request();
                } else {
                    if (!mRecorder.canStop()) {
                        ToastUtils.showShort(getString(R.string.piano_rec_time_too_short_tip_fmt, mRecorder.getMinRecDuration() / 1000));
                        return;
                    }
                    mRecorder.stop();
                    String fileName = FileUtils.getFileNameNoExtension(mRecorder.getRecFilePath());
                    String extension = FileUtils.getFileExtension(mRecorder.getRecFilePath());
                    RecordDialog recordDialog = new RecordDialog(this);
                    recordDialog.setListener(new RecordDialog.IListener() {
                        @Override
                        public void onClickConfirm(String newFileName) {
                            if (fileName.equals(newFileName)) {
                                recordDialog.dismiss();
                                return;
                            }
                            String newFilePath = mRecorder.getRecFolder() + File.separator + newFileName + "." + extension;
                            List<File> files = FileUtils.listFilesInDir(mRecorder.getRecFolder());
                            for (File file : files) {
                                if (file.getAbsolutePath().equals(newFilePath)) {
                                    ToastUtils.showShort(R.string.piano_file_name_exist_tip);
                                    return;
                                }
                            }
                            FileUtils.rename(mRecorder.getRecFilePath(), newFileName + "." + extension);
                            recordDialog.dismiss();
                            ToastUtils.showShort(R.string.record_success);
                        }
                    });
                    recordDialog.setCurrentFileName(fileName);
                    recordDialog.setType(Content.record_type_create);
                    recordDialog.show();
                    break;
                }
                break;
            case R.id.ivPianoAdd:
                mDataBinding.pianoKeyBoard.setKeyCount(mDataBinding.pianoKeyBoard.getKeyCount() + 1);
                mDataBinding.pianoSeekBar.setRatioKeyCountInScreen(mDataBinding.pianoKeyBoard.getRatioKeyCountInScreen());
                break;
            case R.id.ivPianoReduce:
                mDataBinding.pianoKeyBoard.setKeyCount(mDataBinding.pianoKeyBoard.getKeyCount() - 1);
                mDataBinding.pianoSeekBar.setRatioKeyCountInScreen(mDataBinding.pianoKeyBoard.getRatioKeyCountInScreen());
                break;
            case R.id.ivPianoRecordList://录音列表
                startActivity(RecordListActivity.class);
                break;
        }
    }

    @Override
    protected void initData() {
        mRecorder = AudioRecorder.getInstance();
        mRecorder.setRecFolderName(PianoConst.REC_FOLDER);
        //设置最小录制时长不能少于3秒
        mRecorder.setMinRecDuration(3 * 1000);
        mRecorder.addStateListener(this);
        today = TimeUtils.string2Millis(TimeUtils.getNowString(new SimpleDateFormat("yyyy.MM.dd")),new SimpleDateFormat("yyyy.MM.dd"));
        startTime = TimeUtils.getNowMills();
        saveRecord();
    }

    @Override
    public void onStateChanged(RecState state) {
        if (state == RecState.RECORDING) {
            mHandler.post(mTaskUpdateTime);
        } else {
            mHandler.removeCallbacks(mTaskUpdateTime);
            mDataBinding.tvPianoRecordTime.setText("00:00");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRecorder.delStateListener(this);
        mRecorder.release();
        mHandler.removeCallbacks(mTaskUpdateTime);
        endTime = TimeUtils.getNowMills();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
                PracticeTime practiceTime;
                List<PracticeTime> practiceTimeList = PracticeDatabase.getInstance(PianoActivity.this).getPracticeDao().getTodayPracticeTime(today);
                if (practiceTimeList.size()==0) {
                    practiceTime = new PracticeTime(today, endTime - startTime, 0);
                    PracticeDatabase.getInstance(mContext).getPracticeDao().insertPracticeTime(practiceTime);
                }else {
                    practiceTime=practiceTimeList.get(0);
                    practiceTime.setDuration(practiceTime.getDuration()+endTime-startTime);
                    PracticeDatabase.getInstance(mContext).getPracticeDao().updatePracticeTime(practiceTime);
                }
//            }
//        }).start();
    }

    private void saveRecord() {
        List<String> listSave = new ArrayList<>();
        String date=TimeUtils.getNowString(new SimpleDateFormat("yyyy.MM.dd"));
        listSave.add(date);
        List<String> listSp = AppSpUtils.getPracticeList();
        if (listSp != null && listSp.size() > 0) {
            if (!listSp.contains(date)){
                listSp.add(date);
            }
            AppSpUtils.savePracticeList(listSp);
        } else {
            AppSpUtils.savePracticeList(listSave);
        }
    }

}